package com.DFB.controller;


import com.DFB.common.Util.JwtUtils;
import com.DFB.common.Util.ValidateCodeUtils;
import com.DFB.common.exception.CustomException;
import com.DFB.common.model.Result;
import com.DFB.common.model.ResultCode;
import com.DFB.common.model.dto.staffDfb.StaffDfbAddRequest;
import com.DFB.common.model.dto.staffDfb.StaffDfbQueryByIdRequest;
import com.DFB.common.model.dto.staffDfb.StaffDfbQueryRequest;
import com.DFB.pojo.StaffDfb;
import com.DFB.service.StaffDfbService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 员工信息（DFB方） 前端控制器
 * </p>
 *
 * @author DFB
 * @since 2023-07-31
 */
@Slf4j
@RestController
@RequestMapping("/staffDfb")
public class StaffDfbController {

    @Autowired
    private StaffDfbService staffDfbService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody StaffDfb staffDfb) {
        //获取手机号
        String phone = staffDfb.getPhone();

        if (StringUtils.isNotEmpty(phone)) {

            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("code={}", code);

            //调用腾讯云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("DFB",phone,code);

            //保存到Redis中, 设置时间为5min
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("login")
    public Result<String> login(StaffDfb staffDfb, String code) {
        String phone = staffDfb.getPhone();
        String password = staffDfb.getPassword();
        //比对验证码是否正确
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够比对成功, 执行登录
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            LambdaQueryWrapper<StaffDfb> lambdaQueryWrapper = new LambdaQueryWrapper<StaffDfb>();
            lambdaQueryWrapper.eq(StaffDfb::getPhone, phone).eq(StaffDfb::getPassword, password);
            staffDfb = staffDfbService.getOne(lambdaQueryWrapper);
            if (staffDfb != null) {
                //下发令牌
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", staffDfb.getId());
                claims.put("name", staffDfb.getName());
                claims.put("username", staffDfb.getUsername());
                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }
        } else {
            return Result.error(ResultCode.AUTH_CODE_ERROR);
        }
        return Result.error(ResultCode.USER_LOGIN_ERROR);
    }
    /**
     * 新增员工
     *
     */
    @PostMapping("/add")
    public Result<Long> add(@RequestBody StaffDfbAddRequest staffDfbAddRequest) {
        StaffDfb staffDfb = new StaffDfb();
        BeanUtils.copyProperties(staffDfbAddRequest, staffDfb);
        staffDfbService.save(staffDfb);
//        User loginUser = userService.getLoginUser(request);
//        staffDfb.setCreateStaff(loginUser.getUid());

//        staffDfb.setCreateStaff();
        boolean result = staffDfbService.save(staffDfb);
//        ThrowUtils.throwIf(!result, ResultCode.OPERATION_ERROR);
        Long newStaffDfbId = staffDfb.getId();
        return Result.success(newStaffDfbId);
    }

    /**
     *  根据id查询员工
     */
    @PostMapping("/queryStaffDfbById")
    public Result<StaffDfb> queryStaffDfbById(@RequestBody StaffDfbQueryByIdRequest staffDfbQueryByIdRequest, HttpServletRequest request) {
        StaffDfb SD = new StaffDfb();
        SD = staffDfbService.getById(staffDfbQueryByIdRequest.getId());
        return Result.success(SD);
    }

//    /**
//     * 获取用户列表
//     *
//     * @param staffDfbQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/page")
//    public Result listStaffDfbByPage(@RequestBody StaffDfbQueryRequest staffDfbQueryRequest, HttpServletRequest request) {
//        Result result = new Result(); // 创建一个Result对象
//
//        try {
//            List<StaffDfb> staffDfbList = staffDfbService.getQueryStaffDfbList();
//            result.setMessage("获取用户列表成功"); // 设置成功消息
//            result.setData(staffDfbList); // 将用户列表设置到Result对象中
//        } catch (Exception e) {
//            result.setMessage("获取用户列表失败：" + e.getMessage()); // 设置失败消息
//        }
//
//        return result; // 返回封装了用户列表的Result对象
//    }
}

